package cc.wenshixin.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cc.wenshixin.entity.AdminUser;
import cc.wenshixin.service.AdminUserService;

public class AdminUserAction extends ActionSupport implements ModelDriven<AdminUser>{
	//属性注入
	private AdminUserService adminUserService;
	public void setAdminUserService(AdminUserService adminUserService) {
		this.adminUserService = adminUserService;
	}
	//模型驱动封装
	private AdminUser adminUser = new AdminUser();
	@Override
	public AdminUser getModel() {
		return adminUser;
	}

	//登录的方法
	public String login() {
		AdminUser adminUserExist = adminUserService.login(adminUser);
		if(adminUserExist != null) {
			HttpServletRequest request = ServletActionContext.getRequest();
			request.getSession().setAttribute("user", adminUserExist);
			return "loginSuccess";
		}
		return "loginFail";
	}
	
	//跳转到添加页面
	public String toAddPage() {
		return "toAddPage";
	}
	
	//添加的方法
	public String add() {
		adminUserService.add(adminUser);
		return "add";
	}
	
	//显示列表的方法
	public String list() {
		List<AdminUser> adminUserList =  adminUserService.findAll();
		HttpServletRequest request = ServletActionContext.getRequest();
		request.setAttribute("adminUserList", adminUserList);
		return "list";
	}
	
	//跳转到修改页面
	public String toEditPage() {
		int id = adminUser.getId();
		AdminUser adminUser = adminUserService.findOne(id);
		HttpServletRequest request = ServletActionContext.getRequest();
		request.setAttribute("adminUser", adminUser);
		return "toEditPage";
	}
	
	//修改的方法
	public String update() {
		adminUserService.update(adminUser);
		return "update";
	}
	
	//删除的方法
	public String delete() {
		int id = adminUser.getId();
		AdminUser adminUser = adminUserService.findOne(id);
		if(adminUser != null) {
			adminUserService.delete(adminUser);
		}
		return "delete";
	}
	
	//转到修改密码的页面
	public String toChangePasswordPage() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String name = request.getParameter("name");
		AdminUser adminUser = adminUserService.findByName(name);
		if(adminUser != null) {			
			request.setAttribute("adminUser", adminUser);
		}
		return "toChangePasswordPage";
	}
	
	//安全退出的方法
	public String quit() {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession(false);
		session.removeAttribute("user");
		session.invalidate();
		return "quit";
	}
}
